//
//  TrackListVC.m
//  KEREN
//
//  Created by MW on 2023/4/6.
//

#import "TrackListVC.h"
#import "TrackCell.h"
#import "TrackDetailVC.h"
#import "TrackModel.h"
@interface TrackListVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UILabel *dateLbl;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) DeviceInfo *deviceInfo;
@property (nonatomic, strong) NSMutableArray *dataArrM;
@property (nonatomic, assign) int index;
@end

@implementation TrackListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 60)];
    [self.view addSubview:topView];
    topView.backgroundColor = Whire_Color;
    topView.userInteractionEnabled = YES;
    UILabel *datechooseLbl = [UILabel setLblText:@"日期选择" font:Font(16) withColor:Color_333333 inSubView:topView];
    [datechooseLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.centerY.equalTo(topView);
    }];
    _index = 1;
    UIImageView *rightIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Vector"]];
    [topView addSubview:rightIcon];
    [rightIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.width.offset(8);
        make.height.offset(14);
        make.centerY.equalTo(topView);
    }];
    _dateLbl = [UILabel setLblText:[DeteManager shareInstance].getTodayStr font:Font(14) withColor:Color_86898E inSubView:topView];
    [_dateLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(rightIcon.mas_right).offset(-12);
        make.centerY.equalTo(topView);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [topView addGestureRecognizer:tap];
    [self tableView];
    _deviceInfo = [[UserInfoManager sharedInstance] currentDeviceInfo];
    if(_deviceInfo){
        [self getDeviceroutelist];
    }else{
        if([UserInfoManager sharedInstance].deviceInfoList.count > 0){
            _deviceInfo = [UserInfoManager sharedInstance].deviceInfoList.lastObject;
        }
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[KRAlartManager shareInstance] resettingDeteRow];
}

- (void)getDeviceroutelist{
    WEAKSELF
    NSInteger startTime = [[DeteManager shareInstance] monthDayWithdeteStr:_dateLbl.text];
    NSInteger endTime = [[DeteManager shareInstance] monthDayWithendDeteStr:_dateLbl.text];
    NSDictionary *parameters = @{@"index":@(_index),@"size":@(20),@"ebike_id":@(_deviceInfo.Id),@"start_time":@(startTime),@"end_time":@(endTime)};
    [NetworkingTool POST:Get_Device_route_list parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];
        [[KRAlartManager shareInstance] hidenLodingImageView];
        if([response[@"code"] intValue] == 0){
            NSArray *arr = response[@"data"][@"list"];
            if(weakSelf.index == 1){
                [weakSelf.dataArrM removeAllObjects];
            }
            for (int i = 0; i < arr.count; i ++) {
                TrackModel *model = [TrackModel initWithDictionary:arr[i]];
                [weakSelf.dataArrM addObject:model];
            }
            if(arr.count < 20){
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            if (weakSelf.dataArrM.count == 0) {
                [weakSelf.tableView.mj_footer setHidden:YES];
            }else{
                [weakSelf.tableView.mj_footer setHidden:NO];
            }
            if(weakSelf.dataArrM.count == 0){
                KRNodataView *view = [[KRNodataView alloc] initWithFrame:CGRectZero];
                weakSelf.tableView.tableHeaderView = view;
            }else{
                weakSelf.tableView.tableHeaderView = nil;
            }
            [weakSelf.tableView reloadData];
        }else{
            KRNodataView *view = [[KRNodataView alloc] initWithFrame:CGRectZero];
            weakSelf.tableView.tableHeaderView = view;
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];
        [[KRAlartManager shareInstance] hidenLodingImageView];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArrM.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor clearColor];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    footView.backgroundColor = [UIColor clearColor];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TrackCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TrackCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.routeBtn addTarget:self action:@selector(routeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    TrackModel *model = self.dataArrM[indexPath.section];
    cell.startPointLbl.text = model.start_name;
    cell.startPointLbl.numberOfLines = 0;
    cell.endPointLbl.text = model.end_name;
    cell.endPointLbl.numberOfLines = 0;
    [cell.deviceIcon sd_setImageWithURL:[NSURL URLWithString:_deviceInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"] options:SDWebImageRefreshCached];
    cell.timeLbl.text = [[DeteManager shareInstance] timeFormathhmm:model.start_time];
    //timesLbl
    cell.mileageLbl.text = [NSString stringWithFormat:@"%0.1fkm",model.mileage / 1000.0];
    cell.timesLbl.text = [NSString stringWithFormat:@"%ldmin",(long)(model.end_time - model.start_time) / 60];
    cell.speedperhourLbl.text = [NSString stringWithFormat:@"%ldkm/h",model.avg_speed];
    cell.timesLbl.attributedText = [NSAttributedString getAttributeWith:@[@"min"] string:cell.timesLbl.text attributeFont:Font(14)];
    cell.speedperhourLbl.attributedText = [NSAttributedString getAttributeWith:@[@"km/h"] string:cell.speedperhourLbl.text attributeFont:Font(14)];
    cell.mileageLbl.attributedText = [NSAttributedString getAttributeWith:@[@"km"] string:cell.mileageLbl.text attributeFont:Font(14)];
    cell.routeBtn.tag = indexPath.section;
    return cell;
}

- (void)routeBtnClick:(UIButton *)sender{
    TrackDetailVC *vc = [[TrackDetailVC alloc] init];
    vc.model = self.dataArrM[sender.tag];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)tapClick{
    WEAKSELF
    [[KRAlartManager shareInstance] showPickAlertView:@"选择日期" withcurrentIndex:1 IscanChooseHistory:YES  changeTitleBlock:^(NSString * _Nonnull title) {
        weakSelf.dateLbl.text = title;
        [weakSelf getDeviceroutelist];
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];

    }];
}
- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, DEVICE_WIDTH, self.view.frame.size.height - 60 - NAVTOP_Height - 48) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 245;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"TrackCell" bundle:nil] forCellReuseIdentifier:@"TrackCell"];
        WEAKSELF
        _tableView.mj_header =
        [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.index = 1;
            [self getDeviceroutelist];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            weakSelf.index ++;
            [self getDeviceroutelist];

        }];
        _tableView.mj_footer.hidden = YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)dataArrM{
    if(!_dataArrM){
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}
@end
